package bTree.LeetCode;

import javax.swing.tree.TreeNode;

public class 二叉搜索树的最近公共祖先 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        int val=root.val;
        int leftVal=Math.min(p.val,q.val);
        int rightVal=Math.max(p.val,q.val);
        if(root.val==leftVal){
            return root;
        }
        if(val>leftVal&&val<rightVal) {
            return root;
        } else if (val>leftVal&&val>rightVal) {
            return lowestCommonAncestor(root.left,p,q);
        } else if (val==leftVal||val==rightVal) {
            return root;
        } else {
            return lowestCommonAncestor(root.right,p,q);
        }
    }
}